package com.longshine;

/**
 * @Author xiongmin
 * @Description TODO
 * @Date 2019/11/7 12:24
 * @Version 1.0
 **/
public class ThreadDemo01 {

    private int j;

    public static void main(String[] args) {
        ThreadDemo01 threadDemo01 = new ThreadDemo01();
        new Thread(new Thread1(threadDemo01),"Thread--1").start();
        new Thread(new Thread1(threadDemo01),"Thread--2").start();
        new Thread(new Thread2(threadDemo01),"Thread--3").start();
        new Thread(new Thread2(threadDemo01),"Thread--4").start();
    }
    public synchronized void upJ() {
        j++;
    }

    public synchronized void downJ() {
        j--;
    }

    public int getJ() {
        return j;
    }

    static class Thread1 implements Runnable {
        private ThreadDemo01 threadDemo01;

        public Thread1(ThreadDemo01 threadDemo01) {
            this.threadDemo01 = threadDemo01;
        }

        @Override
        public void run() {
            while (true) {
                threadDemo01.upJ();
                System.out.println(Thread.currentThread().getName() + "使得j增加1，当前的j值为：" + threadDemo01.getJ());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    static class Thread2 implements Runnable {
        private ThreadDemo01 threadDemo01;

        public Thread2(ThreadDemo01 threadDemo01) {
            this.threadDemo01 = threadDemo01;
        }

        @Override
        public void run() {
            while (true) {
                threadDemo01.downJ();
                System.out.println(Thread.currentThread().getName() + "使得j减少1，当前的j值为：" + threadDemo01.getJ());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
